package com.dashan.backend.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class EncriptionHelper {
    
    private static String RAND_CHARSET = "abcdefghijklmnopqrstuvwxyz" +
    		                             "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
    		                             "1234567890";
    
    public static String randomString(int length) {
        return randomString(length, RAND_CHARSET.toCharArray());
    }
    
    public static String randomString(int length, char[] charSet) {
        
        char[] res = new char[length];
        SecureRandom rand;
        try {
            rand = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "NoSuchAlgorithmException SHA1PRNG";
        }
        
        for (int i = 0; i < length; i++) {
            int idx = Math.abs(rand.nextInt()) % charSet.length;
            res[i] = charSet[idx];
        }
        
        return new String(res);
    }

    /** Returns an base64 encoded string. **/
    public static String saltPwd(String pwdSha, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(pwdSha.getBytes("UTF-8"));
            md.update(salt.getBytes("UTF-8"));
            return Base64.encode(md.digest());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
        return null;
    }
}
